package com.ccnf.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ccnf.core.utils.ResultUtil;
import com.ccnf.core.utils.SystemClock;
import com.ccnf.model.entity.InvitationBrowse;
import com.ccnf.model.entity.InvitationForward;
import com.ccnf.model.entity.InvitationRecord;
import com.ccnf.model.entity.InvitationUser;
import com.ccnf.model.mapper.*;
import com.ccnf.service.InvitationUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class InvitationUserServiceImpl extends ServiceImpl<InvitationUserMapper, InvitationUser> implements InvitationUserService {
    @Autowired
    private InvitationBrowseMapper invitationBrowseMapper;
    @Autowired
    private InvitationForwardMapper invitationForwardMapper;
    @Autowired
    private InvitationReportMapper invitationReportMapper;
    @Autowired
    private InvitationRecordMapper invitationRecordMapper;

    @Override
    public Long findInvitationUserShareId(InvitationUser invitationUser) {
        InvitationUser selectInvitationUser = new InvitationUser();
        selectInvitationUser.setInvitationId(invitationUser.getInvitationId());
        selectInvitationUser.setUserId(invitationUser.getUserId());
        InvitationUser select = baseMapper.selectOne(selectInvitationUser);
        if (select == null) {
            ResultUtil.validateSQL(baseMapper.insert(selectInvitationUser), "录入分享ID失败");
            return selectInvitationUser.getShareId();
        }
        return select.getShareId();
    }

    @Override
    public void saveUserForwardInvitation(InvitationForward invitationForward) {
        invitationForward.setForwardTime(SystemClock.second());
        ResultUtil.validateSQL(invitationForwardMapper.insert(invitationForward), "录入转发记录失败");
        Long invitationId = invitationForward.getInvitationId();
        invitationRecordMapper.incrementForwardCount(invitationId);
        invitationReportMapper.incrementForwardCount(invitationId, SystemClock.zeroSecond());
        Long shareId = invitationForward.getShareId();
        if (shareId != null) {
            baseMapper.incrementForwardCount(shareId, SystemClock.second());// 增加分享人的转发累计次数
        }
    }

    @Override
    public void saveInvitationBrowse(InvitationBrowse invitationBrowse) {
        invitationBrowse.setBrowseTime(SystemClock.second());
        invitationBrowseMapper.insert(invitationBrowse);
        Long shareId = invitationBrowse.getShareId();
        if (shareId != null) {
            baseMapper.incrementBrowseCount(shareId);// 增加分享人的浏览累计次数
        }
    }
}